package com.douhuayuedu.douhua.wxapi;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.taptech.doufu.util.FetchResourceUtil;
import com.taptech.doufu.R;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.bean.ShareBeansInfo;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.ui.view.ImageUtil;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * Created by Wyatt on 2017/6/6/006.
 */

public class WeixinService {

    private volatile static WeixinService singleton;
    private Context mContext;
    private IWXAPI api;
    public static WeixinService getInstance(Context context) {
        if (singleton == null) {
            synchronized (WeixinService.class) {
                if (singleton == null) {
                    singleton = new WeixinService();
                }
            }
        }
        if (!(context instanceof WXEntryActivity)) {
            singleton.mContext = context;
        }
        return singleton;
    }

    public WeixinService() {
        api = WXAPIFactory.createWXAPI(WeMediaApplication.applicationContext, Constant.WX_APP_ID, true);
        api.registerApp(Constant.WX_APP_ID);
    }


    public void payRequest(String json) {
        if (!api.isWXAppInstalled()) {
            UIUtil.toastMessage(mContext, "请先安装微信");
            return;
        }
        JSONObject jsonObject = JSON.parseObject(json);
        PayReq payReq = new PayReq();
        if (jsonObject.containsKey("appid")) {
            payReq.appId = jsonObject.getString("appid");
        }
        if (jsonObject.containsKey("partnerid")) {
            payReq.partnerId = jsonObject.getString("partnerid");
        }
        if (jsonObject.containsKey("prepayid")) {
            payReq.prepayId = jsonObject.getString("prepayid");
        }
        if (jsonObject.containsKey("package")) {
            payReq.packageValue = jsonObject.getString("package");
        }
        if (jsonObject.containsKey("noncestr")) {
            payReq.nonceStr = jsonObject.getString("noncestr");
        }
        if (jsonObject.containsKey("timestamp")) {
            payReq.timeStamp = jsonObject.getString("timestamp");
        }
        if (jsonObject.containsKey("sign")) {
            payReq.sign = jsonObject.getString("sign");
        }
        api.sendReq(payReq);

    }

    /**
     * 发送微信登录请求
     */
    public void sendWeChatLogin() {
        if (api == null) {
            api = WXAPIFactory.createWXAPI(WeMediaApplication.applicationContext, Constant.WX_APP_ID, true);
            api.registerApp(Constant.WX_APP_ID);
        }
        if (! api.isWXAppInstalled()) {
            UIUtil.toastMessage(mContext, "请先安装微信");
            return;
        }
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "carjob_wx_login";
        api.sendReq(req);
    }


    // 分享 微信
    public void shareToWeixin(final ShareBeansInfo shareInfo) {
        if (api == null) {
            api = WXAPIFactory.createWXAPI(WeMediaApplication.applicationContext, Constant.WX_APP_ID, true);
            api.registerApp(Constant.WX_APP_ID);
        }
        if (! api.isWXAppInstalled()) {
            UIUtil.toastMessage(mContext, "请先安装微信");
            return;
        }
        String url = shareInfo.getImagUrl();
        url = Constant.changeUrlHost(url);
        Glide.with(WeMediaApplication.applicationContext).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap logoBitmap, @Nullable Transition<? super Bitmap> transition) {
                if (logoBitmap == null) {
                    logoBitmap = FetchResourceUtil.fetchBitmap(mContext.getResources(),
                            R.drawable.new_icon);
                }
                uploadFriend(shareInfo, logoBitmap);
            }

        });
    }

    public void shareToWeixinDefaulIcon(ShareBeansInfo shareInfo){
        Bitmap logoBitmap = FetchResourceUtil.fetchBitmap(mContext.getResources(),
                R.drawable.new_icon);
        uploadFriend(shareInfo,logoBitmap);
    }

    private void uploadFriend(ShareBeansInfo shareInfo, Bitmap logoBitmap) {
        WXMediaMessage msg = new WXMediaMessage();
        if (shareInfo.getDataType() == Constant.ShareDataType.SHARE_DATA_TYPE_IMAGE) {
            WXImageObject imgObj = new WXImageObject(logoBitmap);
            msg.mediaObject = imgObj;

        }else{
            WXWebpageObject novelpageObj = new WXWebpageObject();
            msg.mediaObject = novelpageObj;
            novelpageObj.webpageUrl = shareInfo.getShareUrl();
            msg.title = shareInfo.getTitle();
            if (!TextUtils.isEmpty(shareInfo.getShartText())) {
                msg.description = shareInfo.getShartText();
            }else{
                msg.description = "我最近在读的小说，介绍给你";
            }
        }
        if (logoBitmap != null) {
            Bitmap thumbBmp = ImageUtil.centerSquareScaleBitmap(logoBitmap, Constant.WXData.THUMB_WIDTH_SIZE);
            msg.thumbData = WXUtil.bmpToByteArray(thumbBmp, false);
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.scene = SendMessageToWX.Req.WXSceneSession; // for wechat friends
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        api.sendReq(req);
    }


    public void shareBigPicToWeixin(Bitmap bmp) {
        //初始化 WXImageObject 和 WXMediaMessage 对象
        WXImageObject imgObj = new WXImageObject(bmp);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        //调用api接口，发送数据到微信
        api.sendReq(req);
    }

    public void shareBigPicToPengyouquan(Bitmap bmp) {
        //初始化 WXImageObject 和 WXMediaMessage 对象
        WXImageObject imgObj = new WXImageObject(bmp);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

//        //设置缩略图
//        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, Constant.WXData.THUMB_WIDTH_SIZE, Constant.WXData.THUMB_HEIGHT_SIZE, true);
//        bmp.recycle();
//        msg.thumbData = WXUtil.bmpToByteArray(thumbBmp, true);

        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneTimeline;
        //调用api接口，发送数据到微信
        api.sendReq(req);
    }

    // 朋友圈
    public void shareToPengyouquan(final ShareBeansInfo shareInfo) {
        if (api == null) {
            api = WXAPIFactory.createWXAPI(WeMediaApplication.applicationContext, Constant.WX_APP_ID, true);
            api.registerApp(Constant.WX_APP_ID);
        }
        if (! api.isWXAppInstalled()) {
            UIUtil.toastMessage(mContext, "请先安装微信");
            return;
        }
        if (api.getWXAppSupportAPI() < Constant.WXData.PENG_YOU_QUAN_MIN_VERSION_CODE) {
            Toast.makeText(mContext,
                    "微信版本过低，请更新至4.2或更高版本！",
                    Toast.LENGTH_LONG).show();
            return;
        }
        String url = shareInfo.getImagUrl();
        url = Constant.changeUrlHost(url);
        Glide.with(WeMediaApplication.applicationContext).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap logoBitmap, @Nullable Transition<? super Bitmap> transition) {
                if (logoBitmap == null) {
                    logoBitmap = FetchResourceUtil.fetchBitmap(mContext.getResources(),
                            R.drawable.new_icon);
                }
                uploadPengyouquan(shareInfo,logoBitmap);
            }
        });
    }

    public void shareToPengyouquanDefaulIcon(ShareBeansInfo shareInfo){
        Bitmap logoBitmap = FetchResourceUtil.fetchBitmap(mContext.getResources(),
                R.drawable.new_icon);
        uploadFriend(shareInfo,logoBitmap);
    }

    private void uploadPengyouquan(ShareBeansInfo shareInfo,Bitmap logoBitmap) {
        WXMediaMessage msg = new WXMediaMessage();
        if (shareInfo.getDataType() == Constant.ShareDataType.SHARE_DATA_TYPE_IMAGE) {
            WXImageObject imgObj = new WXImageObject(logoBitmap);
            msg.mediaObject = imgObj;
        }else{
            WXWebpageObject novelpageObj = new WXWebpageObject();
            novelpageObj.webpageUrl = shareInfo.getShareUrl();
            msg.mediaObject = novelpageObj;
            StringBuilder showTitle = new StringBuilder();
            showTitle.append(shareInfo.getTitle());
            if (!TextUtils.isEmpty(shareInfo.getShartText())) {
                showTitle.append(":");
                showTitle.append(shareInfo.getShartText());
            }
            msg.title = showTitle.toString();
            msg.description = "这本小说太赞了！";
        }
        if (logoBitmap != null) {
            Bitmap thumbBmp = Bitmap.createScaledBitmap(logoBitmap, Constant.WXData.THUMB_WIDTH_SIZE, Constant.WXData.THUMB_HEIGHT_SIZE, true);
            msg.thumbData = WXUtil.bmpToByteArray(thumbBmp, false);
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.scene = SendMessageToWX.Req.WXSceneTimeline; // for pengyou quan
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        api.sendReq(req);

    }

}
